package edu.uwm.cs552;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

import edu.uwm.cs552.GoalCard.Panel;

public class CardStatusPanel extends JPanel implements Observer {
	/**
	 * Keep Eclipse Happy
	 */
	private static final long serialVersionUID = 1L;
	
	private final CardStatus cards;
	private final JPanel[] lines;
	private final GoalCard.Panel[] cardPanels;
	private final ActionListener listener = new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			int cardIndex = ((RadioButton)arg0.getSource()).getIndex();
			int goalIndex = cards.getCard(cardIndex).getSelected();
			cards.setSelected(cardIndex, goalIndex);
		}
	};
	
	public CardStatusPanel(CardStatus c) {
		cards = c;
		cardPanels = new GoalCard.Panel[c.size()];
		lines = new JPanel[c.size()];
		setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
		ButtonGroup g = new ButtonGroup();
		for (int i=0; i < c.size(); ++i) {
			final GoalCard card = c.getCard(i);
			card.addObserver(this);
			cardPanels[i] = card.new Panel();
			lines[i] = new JPanel();
			RadioButton rb = new RadioButton(i);
			lines[i].add(rb);
			rb.addActionListener(listener);
			g.add(rb);
			lines[i].add(cardPanels[i]);
			lines[i].setLayout(new FlowLayout(FlowLayout.LEFT));
			add(lines[i]);
		}
		c.addObserver(this);
	}
	
	public void update(Observable obs, Object obj) {
		if (obs == cards && obj instanceof Integer) {
			int i = ((Integer)obj).intValue();
			if (i < 0 || i >= cards.size()) return;
			lines[i].remove(cardPanels[i]);
			cardPanels[i].getGoalCard().deleteObservers();
			final GoalCard card = cards.getCard(i);
			card.addObserver(this);
			cardPanels[i] = card.new Panel();
			lines[i].add(cardPanels[i]);
			// lines[i].validate();
			this.validate();
		} else if (obs == cards.getSelectedCard()) {
			for (int i=0; i < cards.size(); ++i) {
				if (cards.getCard(i) == obs) {
					cards.setSelected(i, ((GoalCard)obs).getSelected());
				}
			}
		}
	}
	
	private class RadioButton extends JRadioButton {
		/**
		 * Keep Eclipse happy
		 */
		private static final long serialVersionUID = 1L;
		private final int index;
		public RadioButton(int i) {
			super();
			index = i;
		}
		public int getIndex() {
			return index;
		}
	}

}
